﻿using System;

namespace Presentation.Web.Core.CDN
{
    public class UrlProvider : FileDependencyCacheBase<string>
    {
        public static readonly UrlProvider Instance = new UrlProvider();
        protected UrlProvider() { }
        protected override string GetDependencyPath(string key)
        {
            return PathHelper.GetExistingPhysicalPath(key);
        }
        protected override string LoadItem(string key)
        {
            string basePath = PathHelper.GetCachableBasePath(key);

            if (basePath == null)
            {
                return key;
            }

            string filePath = PathHelper.GetPhysicalPath(key);

            if (PathHelper.Exists(filePath))
            {
                DateTime version = System.IO.File.GetLastWriteTimeUtc(filePath);
                string relativePath = key.Substring(basePath.Length);
                return PathHelper.GetCachedVirtualPath(basePath, relativePath, version);
            }
            else
            {
                return key;
            }
        }

        public string GetCachableVirtualPath(string relativePath)
        {
            if (PathHelper.IsCachable(relativePath))
            {
                string queryString = String.Empty;
                int idx = relativePath.IndexOf('?');
                if (idx > 0)
                {
                    queryString = relativePath.Substring(idx);
                    relativePath = relativePath.Substring(0, idx);
                }
                return this.GetItem(relativePath) + queryString;
            }
            return relativePath;
        }

    }
}